
//  AsyncGETConnect.m
//  婚礼记
//
//  Created by Lovetong on 15/2/8.
//  Copyright (c) 2015年 mac. All rights reserved.
//

#import "AsyncGETConnect.h"

@interface AsyncGETConnect ()<NSURLConnectionDataDelegate>

@property (retain, nonatomic) NSMutableData *receiveData;
@property (copy, nonatomic) void (^block)(NSData *data);

@end

@implementation AsyncGETConnect

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.receiveData = [NSMutableData data];
    }
    return self;
}

+ (void)asyncGETConnectWithUrlString:(NSString *)urlString parmaters:(NSDictionary *)parmaters getData:(void (^)(NSData *data))block
{
    AsyncGETConnect *asyncGETConnect = [[AsyncGETConnect alloc] init];
    asyncGETConnect.block = Block_copy(block);
    [asyncGETConnect startGetConnectWithUrlString:urlString parmaters:parmaters];
    [asyncGETConnect release];
}

- (void)startGetConnectWithUrlString:(NSString *)urlString parmaters:(NSDictionary *)parmaters
{
    NSString *string = @"";
    for (NSString *key in [parmaters allKeys]) {
        if ([string length] == 0) {
            string = [NSString stringWithFormat:@"?%@=%@", key, [parmaters objectForKey:key]];
        } else {
            string = [NSString stringWithFormat:@"%@&%@=%@", string, key, [parmaters objectForKey:key]];
        }
    }
    urlString = [[NSString stringWithFormat:@"%@%@", urlString, string] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    [urlRequest setHTTPMethod:@"GET"];
    [NSURLConnection connectionWithRequest:urlRequest delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_receiveData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.block(_receiveData);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"error");
}

- (void)dealloc
{
    Block_release(_block);
    [_receiveData release];
    [super dealloc];
}


@end
